package com.qc31.baselib.custom.timer

import java.text.SimpleDateFormat
import java.util.*

/**
 * 说明：日期格式化工具
 * 作者：liuwan1992
 * 添加时间：2018/12/17
 * 修改人：liuwan1992
 * 修改时间：2018/12/18
 */
object DateFormatUtils {
    private const val DATE_FORMAT_PATTERN_YMD = "yyyy-MM-dd"
    private const val DATE_FORMAT_PATTERN_YMD_HM = "yyyy-MM-dd HH:mm"
    private const val DATE_FORMAT_PATTERN_YMD_HMS = "yyyy-MM-dd HH:mm:ss"

    /**
     * 时间戳转字符串
     *
     * @param timestamp     时间戳
     * @param isPreciseTime 是否包含时分
     * @return 格式化的日期字符串
     */
    fun long2Str(timestamp: Long, isPreciseTime: Boolean): String {
        return long2Str(timestamp, getFormatPattern(isPreciseTime))
    }

    private fun long2Str(timestamp: Long, pattern: String): String {
        return SimpleDateFormat(pattern, Locale.CHINA)
            .format(Date(timestamp))
    }

    fun long2Str(timestamp: Long): String {
        return SimpleDateFormat(
            DATE_FORMAT_PATTERN_YMD_HMS,
            Locale.CHINA
        ).format(Date(timestamp))
    }

    /**
     * 字符串转时间戳
     *
     * @param dateStr       日期字符串
     * @param isPreciseTime 是否包含时分
     * @return 时间戳
     */
    fun str2Long(dateStr: String?, isPreciseTime: Boolean): Long {
        return str2Long(dateStr, getFormatPattern(isPreciseTime))
    }

    private fun str2Long(dateStr: String?, pattern: String): Long {
        try {
            return SimpleDateFormat(pattern, Locale.CHINA).parse(dateStr)
                .time
        } catch (ignored: Throwable) {
        }
        return 0
    }

    private fun getFormatPattern(showSpecificTime: Boolean): String {
        return if (showSpecificTime) {
            DATE_FORMAT_PATTERN_YMD_HM
        } else {
            DATE_FORMAT_PATTERN_YMD
        }
    }
}